package com.syh.niceweibo.common;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.Bitmap;
import android.os.Handler;

public class AsyncImageLoader {
	private final static String TAG="AsyncImageLoader";

    private Map<String, SoftReference<Bitmap>> mImageCache;
    private ExecutorService mExecutorService;

    private static AsyncImageLoader instance = null;

    public static AsyncImageLoader getInstance() {
        if (instance == null) {
            instance = new AsyncImageLoader();
        }
        return instance;
    }

    private AsyncImageLoader() {
        mImageCache = new HashMap<String, SoftReference<Bitmap>>();
        mExecutorService = Executors.newFixedThreadPool(2);
    };

    private Handler handle = new Handler() {
    };

    /**
     * 
     * @param c
     * @param imageSource
     * @param callback
     * @return if not null,won't invoke callback
     */
    public Bitmap loadBitmap(final String imageSource,final ImageCallback callback,final Object tag,final int outW) {
        try {
            if(LogUtils.DEBUG)LogUtils.d(TAG, "loadBitmap imageSource:" + imageSource);

            // load image from cache
            if (mImageCache.containsKey(imageSource)) {
                SoftReference<Bitmap> softReference = mImageCache.get(imageSource);
                if (softReference.get() != null) {
                    if(LogUtils.DEBUG)LogUtils.d(TAG, "load img from cache,imageSource:" + imageSource);
                    return softReference.get();
                }
            }

            // load image from local
            Bitmap bitmapFromSDcard = Utils.getLocalImg(imageSource,outW);
            if (bitmapFromSDcard != null) {
            	if(LogUtils.DEBUG)LogUtils.d(TAG, "load img from local");
                return bitmapFromSDcard;
            }

            // load image from internet
            mExecutorService.submit(new Runnable() {
                public void run() {
                    
                    try {
                        if(LogUtils.DEBUG)LogUtils.d(TAG, "load img from Local,imageSource:" + imageSource);

                        try {
							Utils.download(imageSource);
						} catch (Exception e) {
							e.printStackTrace();
							if(LogUtils.DEBUG)LogUtils.e(TAG,"download imageSource:"+imageSource+" e:"+e.toString());
						}
                        Bitmap bitmap=Utils.getLocalImg(imageSource,outW);
                        if (bitmap != null) {
                            mImageCache.put(imageSource, new SoftReference<Bitmap>(bitmap));
                            bitmap=null;
                            if(callback!=null){
                            	if(mImageCache==null){
                            		LogUtils.e(TAG,"mImageCache is null");
                            	}
                            	if(mImageCache.get(imageSource)==null){
                            		LogUtils.e(TAG,"SoftReference is null imageSource："+imageSource);
                            	}
                                final Bitmap btp = mImageCache.get(imageSource).get();
                                handle.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.imageLoaded(btp, tag);
                                    }
                                });
                            }
                        }else{
                        	if(LogUtils.DEBUG)LogUtils.d(TAG,"getLocalImg is null");
                        }
                        
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                        if(LogUtils.DEBUG)LogUtils.e(TAG, "mExecutorService load img error:" + e.toString());
                    }
                }
            });
        } catch (Exception e1) {
            e1.printStackTrace();
            if(LogUtils.DEBUG)LogUtils.e(TAG, "loadBitmap error:" + e1.toString());
        }
        return null;
    }

    public static interface ImageCallback {
        // invoked in UI-Thread
        public void imageLoaded(Bitmap imageBitmap, Object tag);
    }

    public void flush() {
        try {
            mImageCache.clear();
        } catch (Exception e) {
            e.printStackTrace();
            if(LogUtils.DEBUG)LogUtils.e(TAG, "AsyncImageLoader flush error:" + e.toString());
        }
    }

    public static void close() {
        if (instance != null) {
            try {
                instance.mExecutorService.shutdown();
                
            } catch (Exception e) {
                e.printStackTrace();
                if(LogUtils.DEBUG)LogUtils.e(TAG, "AsyncImageLoader close error:" + e.toString());
            }
            
            try {
                instance.mImageCache.clear();
                instance.mImageCache = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
